package com.sparrow.manage.common.controller;

import com.sparrow.manage.common.entity.StandardEntity;
import com.sparrow.manage.common.entity.result.Result;
import com.sparrow.manage.common.service.BaseService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

public abstract class StandardController<T extends StandardEntity> extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(StandardController.class);

    /**
     * 获取操作实体的实际service层对象
     * @return
     */
    protected abstract BaseService getService();

    /**
     * 实体"增, 改"时的各项校验
     * 该方法体内部不需要再次对引用进行非空校验, 出入该方法的一定是对象, 不会为null
     * @param t
     * @return 返回值如果为null, 将认为是验证通过; 只有返回值是isSuccess == false时会认为验证未通过
     */
    protected abstract Result argumentsValidate(T t);

    private Result argumentsCheck(T t){
        if(t == null) return Result.NULL_OPERATE_RESULT;

        Result argCheckResult = argumentsValidate(t);
        if(argCheckResult != null && !argCheckResult.isSuccess()){
            return argCheckResult;
        }else{
            return null;
        }
    }

    /**
     * 新增实体
     * @param t
     * @return
     */
    protected final Result addEntity(T t){
        Result checkResult = argumentsCheck(t);
        if(checkResult != null){
            return checkResult;
        }

        Result result = new Result();
        try{
            pushCreateUser(t);
            getService().insert(t);
            result.setSuccess(true);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
        }

        return result;
    }

    protected void pushCreateUser(T t){
        t.setCreateTime(new Date());
        t.setCreateUser(getCurrentUser().getId());
    }

    /**
     * 根据主键id删除实体
     * @param id
     * @return
     */
    protected final Result removeEntity(String id){
        if(StringUtils.isBlank(id)) return Result.NULL_OPERATE_RESULT;

        Result result = new Result();
        try{
            getService().delete(id);
            result.setSuccess(true);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 根据主键id修改实体
     * @param t
     * @return
     */
    protected final Result updateEntity(T t){
        Result checkResult = argumentsCheck(t);
        if(checkResult != null){
            return checkResult;
        }

        Result result = new Result();
        try{
            pushUpdateUser(t);
            getService().updateById(t);
            result.setSuccess(true);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    protected void pushUpdateUser(T t){
        t.setUpdateTime(new Date());
        t.setUpdateUser(getCurrentUser().getId());
    }

}
